<template>
  <div class="order-container">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <div class="stats-card">
          <div class="stats-icon">
            <i class="el-icon-document"></i>
          </div>
          <div class="stats-info">
            <div class="stats-value">{{ statistics.activeOrders }}</div>
            <div class="stats-label">活跃订单</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stats-card">
          <div class="stats-icon success">
            <i class="el-icon-check"></i>
          </div>
          <div class="stats-info">
            <div class="stats-value">{{ statistics.completedOrders }}</div>
            <div class="stats-label">已成交</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stats-card">
          <div class="stats-icon danger">
            <i class="el-icon-close"></i>
          </div>
          <div class="stats-info">
            <div class="stats-value">{{ statistics.cancelledOrders }}</div>
            <div class="stats-label">已取消</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stats-card">
          <div class="stats-icon warning">
            <i class="el-icon-money"></i>
          </div>
          <div class="stats-info">
            <div class="stats-value">{{ todayVolume }}</div>
            <div class="stats-label">今日成交额</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 筛选条件 -->
    <div class="filter-container">
      <!-- 状态筛选标签和导出按钮 -->
      <div class="filter-row status-row">
        <div class="status-tabs">
          <div 
            class="status-tab" 
            :class="{ active: filterStatus === 'all' }"
            @click="filterStatus = 'all'"
          >
            <span>全部</span>
            <el-badge :value="0" class="status-count" type="primary" />
          </div>
          <div 
            class="status-tab" 
            :class="{ active: filterStatus === 'pending' }"
            @click="filterStatus = 'pending'"
          >
            <span>待成交</span>
            <el-badge :value="0" class="status-count" type="info" />
          </div>
          <div 
            class="status-tab" 
            :class="{ active: filterStatus === 'partial' }"
            @click="filterStatus = 'partial'"
          >
            <span>部分成交</span>
            <el-badge :value="0" class="status-count" type="warning" />
          </div>
          <div 
            class="status-tab" 
            :class="{ active: filterStatus === 'completed' }"
            @click="filterStatus = 'completed'"
          >
            <span>已成交</span>
            <el-badge :value="0" class="status-count" type="success" />
          </div>
          <div 
            class="status-tab" 
            :class="{ active: filterStatus === 'cancelled' }"
            @click="filterStatus = 'cancelled'"
          >
            <span>已取消</span>
            <el-badge :value="0" class="status-count" type="danger" />
          </div>
        </div>
        <div class="action-group">
          <el-button
            type="success"
            icon="el-icon-download"
            size="small"
            @click="exportData"
            :loading="exporting"
          >导出数据</el-button>
        </div>
      </div>

      <!-- 搜索和筛选条件 -->
      <div class="filter-row search-filter-row">
        <div class="filter-group">
          <div class="search-item">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索订单ID、交易对、策略名称..."
              prefix-icon="el-icon-search"
              size="small"
            />
          </div>
          <div class="filter-item">
            <el-select v-model="filterType" placeholder="全部类型" size="small">
              <el-option label="全部类型" value="all" />
              <el-option label="限价单" value="limit" />
              <el-option label="市价单" value="market" />
            </el-select>
          </div>
          <div class="filter-item">
            <el-select v-model="filterExchange" placeholder="全部交易所" size="small">
              <el-option label="全部交易所" value="all" />
              <el-option label="Binance" value="binance" />
              <el-option label="OKX" value="okx" />
            </el-select>
          </div>
          <div class="filter-item">
            <el-select v-model="filterPair" placeholder="全部交易对" size="small">
              <el-option label="全部交易对" value="all" />
            </el-select>
          </div>
          <div class="filter-item">
            <el-select v-model="filterTime" placeholder="今天" size="small">
              <el-option label="今天" value="today" />
              <el-option label="近7天" value="week" />
              <el-option label="近30天" value="month" />
              <el-option label="自定义" value="custom" />
            </el-select>
          </div>
        </div>
        <el-button 
          type="primary" 
          icon="el-icon-refresh" 
          size="small" 
          @click="resetFilters"
          class="reset-button"
        >重置筛选</el-button>
      </div>
    </div>

    <!-- 订单列表 -->
    <div class="order-table">
      <el-table
        :data="orderList"
        style="width: 100%"
        border
        v-loading="loading"
      >
        <el-table-column prop="time" label="时间" sortable width="180" />
        <el-table-column prop="pair" label="交易对" width="120" />
        <el-table-column prop="type" label="类型" width="100" />
        <el-table-column prop="direction" label="方向" width="100">
          <template slot-scope="scope">
            <span :class="scope.row.direction === 'buy' ? 'buy-text' : 'sell-text'">
              {{ scope.row.direction === 'buy' ? '买入' : '卖出' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="120" />
        <el-table-column prop="amount" label="数量" width="120" />
        <el-table-column prop="filled" label="已成交" width="120" />
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)" size="small">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="exchange" label="交易所" />
        <el-table-column prop="strategy" label="策略" />
        <el-table-column label="操作" width="150" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small">详情</el-button>
            <el-button type="text" size="small" class="danger-text">取消</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <div class="page-info">显示 1-20 / 共 {{ total }} 条订单</div>
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'OrderManagement',
  data() {
    return {
      // 筛选条件
      filterStatus: 'all',
      filterType: 'all',
      filterExchange: 'all',
      filterPair: 'all',
      filterTime: 'today',
      searchKeyword: '',

      // 统计数据
      statistics: {
        activeOrders: 15,
        completedOrders: 128,
        cancelledOrders: 8,
        todayVolume: '325,420.50'
      },

      // 表格数据
      loading: false,
      orderList: [],
      currentPage: 1,
      pageSize: 20,
      total: 0,

      // 模拟数据
      mockOrders: [
        {
          id: 'ORD202505230001',
          time: '2025-05-23 14:35:22',
          pair: 'BTC/USDT',
          type: '限价单',
          direction: 'buy',
          price: '45,280.50',
          amount: '0.5',
          filled: '0.3',
          status: '部分成交',
          exchange: 'Binance',
          strategy: '趋势跟踪A'
        },
        {
          id: 'ORD202505230002',
          time: '2025-05-23 14:32:15',
          pair: 'ETH/USDT',
          type: '市价单',
          direction: 'sell',
          price: '2,850.25',
          amount: '2.0',
          filled: '2.0',
          status: '已成交',
          exchange: 'OKX',
          strategy: '网格交易B'
        },
        {
          id: 'ORD202505230003',
          time: '2025-05-23 14:30:45',
          pair: 'BNB/USDT',
          type: '限价单',
          direction: 'buy',
          price: '320.80',
          amount: '10',
          filled: '0',
          status: '待成交',
          exchange: 'Binance',
          strategy: '套利策略C'
        },
        {
          id: 'ORD202505230004',
          time: '2025-05-23 14:28:33',
          pair: 'SOL/USDT',
          type: '市价单',
          direction: 'sell',
          price: '98.50',
          amount: '20',
          filled: '0',
          status: '已取消',
          exchange: 'OKX',
          strategy: '趋势跟踪A'
        },
        {
          id: 'ORD202505230005',
          time: '2025-05-23 14:25:18',
          pair: 'BTC/USDT',
          type: '限价单',
          direction: 'sell',
          price: '45,180.30',
          amount: '0.8',
          filled: '0.8',
          status: '已成交',
          exchange: 'Binance',
          strategy: '网格交易B'
        }
      ],
      exporting: false,
    }
  },
  methods: {
    getStatusType(status) {
      const typeMap = {
        '待成交': 'info',
        '部分成交': 'warning',
        '已成交': 'success',
        '已取消': 'danger'
      }
      return typeMap[status] || 'info'
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchOrders()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchOrders()
    },
    fetchOrders() {
      this.loading = true
      
      // 模拟API请求延迟
      setTimeout(() => {
        // 根据筛选条件过滤订单
        let filteredOrders = [...this.mockOrders]
        
        // 状态筛选
        if (this.filterStatus !== 'all') {
          const statusMap = {
            'pending': '待成交',
            'partial': '部分成交',
            'completed': '已成交',
            'cancelled': '已取消'
          }
          filteredOrders = filteredOrders.filter(order => order.status === statusMap[this.filterStatus])
        }

        // 类型筛选
        if (this.filterType !== 'all') {
          filteredOrders = filteredOrders.filter(order => order.type === (this.filterType === 'limit' ? '限价单' : '市价单'))
        }

        // 交易所筛选
        if (this.filterExchange !== 'all') {
          filteredOrders = filteredOrders.filter(order => order.exchange.toLowerCase() === this.filterExchange)
        }

        // 搜索关键词
        if (this.searchKeyword) {
          const keyword = this.searchKeyword.toLowerCase()
          filteredOrders = filteredOrders.filter(order => 
            order.id.toLowerCase().includes(keyword) ||
            order.pair.toLowerCase().includes(keyword) ||
            order.strategy.toLowerCase().includes(keyword)
          )
        }

        // 更新总数和列表数据
        this.total = filteredOrders.length
        const start = (this.currentPage - 1) * this.pageSize
        const end = start + this.pageSize
        this.orderList = filteredOrders.slice(start, end)
        
        this.loading = false
      }, 500)
    },
    // 重置筛选条件
    resetFilters() {
      this.filterStatus = 'all'
      this.filterType = 'all'
      this.filterExchange = 'all'
      this.filterPair = 'all'
      this.filterTime = 'today'
      this.searchKeyword = ''
      this.fetchOrders()
    },
    exportData() {
      this.exporting = true
      
      // 获取所有筛选后的数据
      let filteredOrders = [...this.mockOrders]
      
      // 应用筛选条件
      if (this.filterStatus !== 'all') {
        const statusMap = {
          'pending': '待成交',
          'partial': '部分成交',
          'completed': '已成交',
          'cancelled': '已取消'
        }
        filteredOrders = filteredOrders.filter(order => order.status === statusMap[this.filterStatus])
      }
      
      if (this.filterType !== 'all') {
        filteredOrders = filteredOrders.filter(order => order.type === (this.filterType === 'limit' ? '限价单' : '市价单'))
      }
      
      if (this.filterExchange !== 'all') {
        filteredOrders = filteredOrders.filter(order => order.exchange.toLowerCase() === this.filterExchange)
      }
      
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase()
        filteredOrders = filteredOrders.filter(order => 
          order.id.toLowerCase().includes(keyword) ||
          order.pair.toLowerCase().includes(keyword) ||
          order.strategy.toLowerCase().includes(keyword)
        )
      }
      
      // 构建CSV内容
      const headers = [
        '订单ID',
        '时间',
        '交易对',
        '类型',
        '方向',
        '价格',
        '数量',
        '已成交',
        '状态',
        '交易所',
        '策略'
      ]
      
      const rows = filteredOrders.map(order => [
        order.id,
        order.time,
        order.pair,
        order.type,
        order.direction === 'buy' ? '买入' : '卖出',
        order.price,
        order.amount,
        order.filled,
        order.status,
        order.exchange,
        order.strategy
      ])
      
      // 添加表头
      rows.unshift(headers)
      
      // 转换为CSV格式
      const csvContent = rows.map(row => row.join(',')).join('\n')
      
      // 创建Blob对象
      const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' })
      
      // 创建下载链接
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = `订单数据_${new Date().toLocaleDateString()}.csv`
      
      // 触发下载
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      this.exporting = false
      
      // 提示导出成功
      this.$message({
        message: '数据导出成功',
        type: 'success'
      })
    }
  },
  mounted() {
    this.fetchOrders()
  },
  watch: {
    // 监听筛选条件变化
    filterStatus() { this.fetchOrders() },
    filterType() { this.fetchOrders() },
    filterExchange() { this.fetchOrders() },
    filterPair() { this.fetchOrders() },
    filterTime() { this.fetchOrders() },
    searchKeyword() { this.fetchOrders() }
  }
}
</script>

<style lang="scss" scoped>
.order-container {
  padding: 20px;
  background-color: #f5f7fa;

  .stats-row {
    margin-bottom: 20px;

    .stats-card {
      background: #fff;
      border-radius: 8px;
      padding: 20px;
      height: 100px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
      display: flex;
      align-items: center;

      .stats-icon {
        width: 48px;
        height: 48px;
        border-radius: 8px;
        background-color: #409EFF;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;

        i {
          font-size: 24px;
          color: #fff;
        }

        &.success {
          background-color: #67C23A;
        }

        &.danger {
          background-color: #F56C6C;
        }

        &.warning {
          background-color: #E6A23C;
        }
      }

      .stats-info {
        flex: 1;

        .stats-value {
          font-size: 24px;
          font-weight: 600;
          color: #303133;
          line-height: 1;
          margin-bottom: 8px;
        }

        .stats-label {
          font-size: 14px;
          color: #909399;
        }
      }
    }
  }

  .filter-container {
    background: #fff;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

    .filter-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      &:last-child {
        margin-bottom: 0;
      }

      &.status-row {
        .status-tabs {
          display: flex;
          gap: 8px;
          
          .status-tab {
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 6px;
            background-color: #f5f7fa;
            transition: all 0.3s;
            font-size: 13px;
            
            &:hover {
              background-color: #ecf5ff;
            }
            
            &.active {
              background-color: #409EFF;
              color: #fff;
              
              .el-badge__content {
                background-color: #fff !important;
                color: #409EFF !important;
              }
            }
            
            .status-count {
              transform: scale(0.8);
            }
          }
        }
      }

      &.search-filter-row {
        .filter-group {
          display: flex;
          gap: 8px;

          .search-item {
            .el-input {
              width: 240px;
            }
          }

          .filter-item {
            .el-select {
              width: 140px;
            }
          }
        }

        .reset-button {
          height: 32px;
          margin-left: 8px;
        }
      }
    }
  }

  .order-table {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

    .buy-text {
      color: #67C23A;
    }

    .sell-text {
      color: #F56C6C;
    }

    .danger-text {
      color: #F56C6C;
    }

    .pagination-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 20px;

      .page-info {
        color: #909399;
        font-size: 14px;
      }
    }
  }
}
</style> 